package com.zerosky.crm.controller;

import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.zerosky.crm.po.Customer;
import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.LoginLog;
import com.zerosky.crm.po.OaMenu;
import com.zerosky.crm.po.Relation;
import com.zerosky.crm.po.WeixinCofing;
import com.zerosky.crm.service.CustomerService;
import com.zerosky.crm.service.EmployeeService;
import com.zerosky.crm.service.LoginLogService;
import com.zerosky.crm.service.MenuService;
import com.zerosky.crm.service.RelationService;
import com.zerosky.crm.service.WeixinCofingService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.GOauth2Core;
import com.zerosky.crm.util.ParamesAPI;
import com.zerosky.crm.util.WeixinUtil;

/**
 * 微信功能
 * 
 * @author zhoudexing
 */
@Controller(value = "weixin")
public class WeChatAction extends BaseAction {

	@Resource(name = "employeeService")
	private EmployeeService employeeService;

	@Resource(name = "menuService")
	private MenuService menuService;

	@Resource(name = "relationService")
	private RelationService relationService;

	@Resource(name = "customerService")
	private CustomerService customerService;

	@Resource(name = "loginLogService")
	private LoginLogService loginLogService;

	@Resource(name = "weixinCofingService")
	private WeixinCofingService weixinConfigService;
 
//	private static String REDIRECT_URI = "http://h4nb1.hn3.mofasuidao.cn/FUNDCRM/weixin/UsersVerification";
//	private static String appid = "wxf0ae3e6550525563";
//	private static String secre = "4b881e0eb078ee7f0b2c80f0bebe6cca";
	
	private static String REDIRECT_URI = "http://3h86j6k.hk1.mofasuidao.cn/FUNDCRM/weixin/UsersVerification";
	private static String appid = "wx2a848336ef2fd494";
	private static String secre = "a1e85a2b005c29a79b89588c25396a14"; 
	
	
	
	/**
	 * 企业微信访问
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/access.do")
	public void access(HttpServletResponse response, HttpSession session, HttpServletRequest request) throws Exception {
		//初始化企业微信配置信息。
		WeixinCofing wx =  weixinConfigService.getWeixinCofingByTitle("qiyeweixin");
		ParamesAPI.corpId = wx.getAppId();
		ParamesAPI.secret = wx.getSecret();
		ParamesAPI.REDIRECT_URI = wx.getRedirect_url();
		ParamesAPI.token = wx.getTonke();
		ParamesAPI.AGENT_ID = wx.getAgent_id();
		ParamesAPI.REDIRECT_URI = wx.getRedirect_url();  
		
		String url = GOauth2Core.GetCode();
		// 跳转到授权页面
		response.sendRedirect(url);
	}

	/**
	 * 企业微信登录
	 * 验证id是否有过登录
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/verification.do")
	public ModelAndView verification(HttpServletResponse response, HttpSession session, HttpServletRequest request) {
		try {
			// JSONObject json = new JSONObject();
			// 拿到传进来的code 去进行查找用户的openid
			String code = request.getParameter("code");
			String usersid;
			String mobile;
			JSONObject UserObj = new JSONObject();
			if (!"authdeny".equals(code)) {
				String access_token = WeixinUtil.getAccessToken(ParamesAPI.corpId, ParamesAPI.secret).getToken();
				// agentid 跳转链接时所在的企业应用ID
				// 管理员须拥有agent的使用权限；agentid必须和跳转链接时所在的企业应用ID相同
				JSONObject UserCodeObj = GOauth2Core.GetUserID(access_token, code, ParamesAPI.AGENT_ID);
				usersid = UserCodeObj.getString("UserId");
				UserObj = GOauth2Core.getTicket(access_token, usersid);
				mobile = UserObj.getString("mobile");
			} else { // 授权失败
				return new ModelAndView("WEB-INF/wap/error");
			}

			if (!usersid.equals("") && usersid != null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("usersId", "huguyue");
				System.out.println("用户usersId:" + usersid);
				System.out.println("用户phoneNumber:" + mobile);
				
				Employee emp = employeeService.userLogin(map);
				if (emp == null) {

					map = new HashMap<String, Object>();
					map.put("phoneNumber", mobile);
					emp = employeeService.userLogin(map);
					Employee user = (Employee) session.getAttribute("loginUser");
					emp.setUpdateEmpId(user.getEmployeeId());
					emp.setUpdateDate(new Date());
					emp.setUsersId(usersid);
					employeeService.saveEmployee(emp, "修改");
				}
				if (emp != null) {
					session.setAttribute("loginUser", emp);
					List<Relation> relation = relationService.getRelationByRoleIdList(emp.getRole().getId());
					List<OaMenu> oaMenu = menuService.getMenuList();
					// 生成菜单
					List<OaMenu> menu = shengcMenu(oaMenu, relation);
					session.setAttribute("users", emp);
					session.setAttribute("menu", menu);
				}
			}

			return new ModelAndView("WEB-INF/wap/index");
		} catch (Exception e) {
			ModelAndView mv = new ModelAndView("WEB-INF/wap/error");
			mv.addObject("msg", "系统未查找到微信帐号信息!");
			mv.addObject("msg2", "请联系管理员添加信息");
			return mv;
		}

	}
	
	/**
	 * 微信url验证
	 * 
	 * @param response
	 * @param session
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/checkSignature.do")
	public void register(HttpServletResponse response, HttpSession session,
			HttpServletRequest request) throws Exception {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (WeixinUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		System.out.println("checkSignature success");
		out.close();
		out = null;
	}
	
	
	
	
	/**
	 * 用户访问，不影响原先企业登录。
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/UserAccess.do")
	public void serviceAccess(HttpServletResponse response, HttpSession session,
			HttpServletRequest request) throws Exception {
		WeixinCofing wx =  weixinConfigService.getWeixinCofingByTitle("weixin");
		appid = wx.getAppId();
		secre = wx.getSecret();
		REDIRECT_URI = wx.getRedirect_url();
		
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+ wx.getAppId() //使用id
				+ "&redirect_uri="
				+ wx.getRedirect_url()
				+ "&response_type=code"
				+ "&scope="
				+ wx.getScope()
				+"&state=STATE#wechat_redirect";
		//session.setAttribute("wxconfig", wx); 
		response.sendRedirect(url);
	}
	
	
	/**
	 * 验证id是否有过登录
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/UsersVerification")
	public ModelAndView UsersVerification(HttpServletResponse response,
			HttpSession session, HttpServletRequest request) throws Exception {
 		ModelAndView mv = new ModelAndView("WEB-INF/wap/mainCustomer");
		
		//拿到传进来的code 去进行查找用户的openid
		String code = request.getParameter("code");
		System.out.println("get code:" + code);
		
		//请求URL 获取到oauth2 用户信息
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
				+ appid + "&secret=" + secre + "&code=" + code
				+ "&grant_type=authorization_code";
		
		String openid = "";  
		//发送
		String content = WeixinUtil.sendPost(url);
		
		// 判定是否正确
		if (content.indexOf("errcode") == -1) {
			
			System.out.println("正确通过...");
			JSONObject json = JSONObject.parseObject(content);
			
			
			openid = json.getString("openid");
			String access_tokens = json.getString("access_token");// 获取用户信息需用该参数（不同于基础的access_token）
			String refresh_token = json.getString("refresh_token");// 刷新access_token（该参数使用时间很短）用
			//输出oauth2信息
			System.out.println("openid:"+openid);
			System.out.println("access_tokens:"+access_tokens);
			System.out.println("refresh_token:"+refresh_token);

			session.setAttribute("openid", openid);
			session.setAttribute("access_tokens", access_tokens);
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("openid", openid);
			Customer customer=customerService.customerLogin(map);
			if(customer!=null){
				
				//登录操作
				session.setAttribute("loginCustomer", customer);
				//json.put("customer", customer);
				//json.put("code", 2);
				//写入登录日志
				//String strIp=request.getRemoteAddr();
				String strIp = getIpAddr(request);
				LoginLog log = new LoginLog(); //创建日志对象
				log.setEmpId(customer.getCustomerId());//获取用户ID
				log.setEmpName(customer.getCustomerName());//获取用户姓名
				log.setLoginIp(strIp);//获取登录ID
				log.setLoginDate(new Date());//获取登录时间
				log.setLoginAddress(getAddrName(strIp));//获取登录地点
				log.setLoginType(1);
				log.setLoginDevice("3");
				loginLogService.saveOrUpdate(log);
			}else{
				url = " https://api.weixin.qq.com/sns/userinfo?access_token="
						+ access_tokens + "&openid=" + openid;
				String val = WeixinUtil.sendPost(url);
				//val.replace("/", "");
				System.out.println("获取到info信息:"+val);
				JSONObject uwx =  JSONObject.parseObject(val);
				customer = new Customer();
				customer.setCustomerId(UUID.randomUUID().toString());
				customer.setMobileNumber("请先绑定手机");
				customer.setAddress("无");
				customer.setProfession("客户");
				customer.setOpenid(openid);
				System.out.println(uwx.getString("nickname"));
				customer.setCustomerName(uwx.getString("nickname"));
				customer.setSex(uwx.getString("sex"));
				customer.setCustomerType("0");
				customer.setCustomerState("0");
				//portrait
				customer.setPortrait(uwx.getString("headimgurl"));
				customerService.saveCustomer(customer, "新增");
				
				//登录操作
				session.setAttribute("loginCustomer", customer);
				//写入登录日志
				//String strIp=request.getRemoteAddr();
				String strIp = getIpAddr(request);
				LoginLog log = new LoginLog(); //创建日志对象
				log.setEmpId(customer.getCustomerId());//获取用户ID
				log.setEmpName(customer.getCustomerName());//获取用户姓名
				log.setLoginIp(strIp);//获取登录ID
				log.setLoginDate(new Date());//获取登录时间
				log.setLoginAddress(getAddrName(strIp));//获取登录地点
				log.setLoginType(1);
				log.setLoginDevice("3");
				loginLogService.saveOrUpdate(log);
			}
			//微信URL中有参数侧跳到指定的页面中去。
			if ((String)session.getAttribute("toUrl")!=null) {
				response.sendRedirect(session.getAttribute("toUrl").toString());
			}
				 
		}
		// 不是WebRoot下的,请注意
		return mv;
	}

	// /**
	// * 发送模板消息
	// * @throws Exception
	// */
	// @RequestMapping("/send")
	// public String sned(HttpServletResponse response,HttpSession session,
	// HttpServletRequest request) throws Exception {
	// String url =
	// "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
	// return null;
	// }

	/**
	 * 过滤掉名称中的emoji的表情
	 */
	Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
			Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

	public CharSequence filters(CharSequence source) {
		Matcher emojiMatcher = emoji.matcher(source);
		if (emojiMatcher.find()) {

			return "";
		}
		return source;
	}

 
	@RequestMapping(value={"/jsapi_sign.htm"})
	@ResponseBody
	public Map<String, Object> jsapi_sign(String url,HttpSession session) throws Exception {
			String ticket = getUsersTicket(session);
			//logger.debug("url="+url+", ticket="+ticket+", obj="+wxTicket);
			Map<String, Object> wx= jsapiSign(ticket, url);
			wx.put("appId", appid);
//	        if( SecurityUserHolder.getCurrentUser() != null ) {
//	        	wx.put( "userId", SecurityUserHolder.getCurrentUser().getId() );
//	        }
	        logger.debug("wx="+wx);
			return wx;
	}
	
	
	public String  getUsersTicket(HttpSession session)
	{
		//String Tickettoken =  (String)session.getAttribute("access_tokens");
		String gettokenurl = WeixinUtil.sendPost("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secre);
		JSONObject tokeJson = JSONObject.parseObject(gettokenurl);
		String Tickettoke = tokeJson.getString("access_token");
		//String Tickettoken = "5__bU0HPRGF9b39r7at_9G4Pcs7NY9RCTQaeDfn0ietUQ5jZwK22oge5gvTpuFynh_h2_rI7v3-ea4eFQDkWfDcJqqd2WBMx9-kZQ4uRxaQ3qycXjTP4Nmi85Wg-nIcR-7qbPNdQV_iT-hwXGBHFJhAEAUSW";
		String content = WeixinUtil.sendPost("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+tokeJson.getString("access_token")+"&type=jsapi");
		JSONObject json = JSONObject.parseObject(content);
		return  json.getString("ticket");
	}
	
	
	 public Map<String, Object> jsapiSign(String ticket, String url) {
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String signature = "";

	        try
	        {
	            //注意这里参数名必须全部小写，且必须有序
	            String string1 = "jsapi_ticket=" + ticket +
	                      "&noncestr=" + nonce_str +
	                      "&timestamp=" + timestamp +
	                      "&url=" + url;
	    		
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        }
	        catch (Exception e)
	        {
	            e.printStackTrace();
	        }
	        Map<String, Object> result=new HashMap<String, Object>();
	        result.put("url", url);
	        result.put("jsapi_ticket", ticket);
	        result.put("nonceStr", nonce_str);
	        result.put("timestamp", timestamp);
	        result.put("signature", signature);
	        return result;
		}
	
	 
	 public static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash)
	        {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	 }
	
	 
	public static String create_nonce_str() {
	        return UUID.randomUUID().toString();
	}

	public static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
}
